<template>
<div class="tag-edit"> 
  <my-header title="现有标签" theme="border-left" size="small"></my-header>
  <div class="tag-list">  
    <el-checkbox-group v-model="selectedList">
      <el-button  style="margin-right: 3px;" size="small" circle type="primary" :icon=" isAddTag ? 'el-icon-minus' : 'el-icon-plus'" @click="isAddTag = !isAddTag"></el-button>
      <el-checkbox style="margin: 3px;" v-for="(item, index) in addedTags" :key="`tag_${index}`" :label="item.id"  border size="small" :title="item.desc">{{item.label}}</el-checkbox>
    </el-checkbox-group>   
    <div style="text-align: right">
      <el-button size="small" type="primary" :disabled="!selectedList.length" @click="selConfirmHandle">确认</el-button>
    </div>
  </div>
  <el-divider></el-divider>
  <div class="add-warp" v-show="isAddTag">
    <my-form  
      @submit="handleSubmit"
      :model="model"
      :rules="rules"
      inline
      label-width="60px"
      item-width="calc(50% - 20px)"
      footer-block
      size="small"
      footer-align="right"
    >
      <my-input name="label" label="标签" width="100%"></my-input>
      <my-input name="desc" label="描述" width="100%" :props="{
        type:'textarea',
        'resize': 'none',
        'rows': 3,
        'maxlength': 20,
        'show-word-limit': true 
      }"></my-input>
    </my-form>
  </div>
  

</div>
</template>
<style lang="scss" scoped>
.tag-edit{
  .tag-list{
    min-height: 50px;
    max-height: 250px;
  }
}

</style>
<script>
import tag from '$my/code/mixin/tag'
export default {
  mixins: [tag],
  components: {},
  props: {
  },
  data() {
    return {
      model: {
        label: '',
        desc: ''
      },
      rules: {
        label: {required: true, message: '标签名是必填项'}
      },
      isAddTag: false,
      addedTags: [],
      selectedList: []
    }
  },
  computed: {
  },
  methods: {
    fetchTagList() {
      this.fetchTag({
        data: {
          page: 1,
          limit: 100
        }
      }).then((res) => { 
        this.addedTags = res.list 
      })
    },
    handleSubmit(res) {
      const obj = {...res}
      obj.label = obj.label.trim() 
      this.addTag({
        data: {
          ...obj
        }
      }).then((res) => {
        this.fetchTagList()
        this.isAddTag = false
        this.model = {
          label: '',
          desc: ''
        }
      })
       
    },
    selConfirmHandle() {
      this.$emit('on-tagSelected', this.getSelectTags())
    },
    setSelectTags(data) {
      this.selectedList = data
    },
    getSelectTags() {
      return this.addedTags.reduce((total, tag) => {
        const target = this.selectedList.find((id) => {
          return id === tag.id
        })
        if (target) {
          total.push(tag)
        } 
        return total
      }, [])
      // return this.selectedList
    }
  },
  created() {},
  mounted() {
    this.fetchTagList()
  }
}
</script>